package com.project.web.wechat.controller.app.cpWeChat;

import com.project.common.core.utils.exception.Result;
import com.project.web.config.WxCorp.WxCpConfig;
import com.project.web.config.WxCorp.WxCpConfiguration;
import com.project.web.util.exception.WeChatCustomException;
import com.project.web.wechat.controller.common.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.WxCpUserService;
import me.chanjar.weixin.cp.bean.WxCpInviteResult;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 成员管理接口
 *
 * @author wyy
 * @date 2020-06-24
 */
@Api(tags = "成员管理接口")
@RestController("workWxUserController")
@RequestMapping("/weChat/auth/workWx/user")
public class WorkWxUserController extends BaseController {

    /**
     * 创建成员¬
     *
     * @return
     */
    @ApiOperation("创建成员")
    @PostMapping(value = "/create")
    public Result<WxCpUser> getAgentInfo(WxCpUser wxCpUser, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpUserService userService = wxCpService.getUserService();
        try {
            userService.create(wxCpUser);
            return getResult(wxCpUser);
        } catch (WxErrorException e) {
            log.error("创建成员出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 读取成员
     *
     * @return
     */
    @ApiOperation("读取成员")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", value = "用户ID", required = true, dataType = "String"),
    })
    @GetMapping(value = "/get")
    public Result<WxCpUser> getUser(String userId, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpUserService userService = wxCpService.getUserService();
        try {
            WxCpUser wxCpUser = userService.getById(userId);
            return getResult(wxCpUser);
        } catch (WxErrorException e) {
            log.error("读取成员出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 更新成员
     *
     * @return
     */
    @ApiOperation("更新成员")
    @PostMapping(value = "/update")
    public Result<WxCpUser> update(WxCpUser wxCpUser, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpUserService userService = wxCpService.getUserService();
        try {
            userService.update(wxCpUser);
            return getResult(wxCpUser);
        } catch (WxErrorException e) {
            log.error("更新成员出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 批量删除成员
     *
     * @return
     */
    @ApiOperation("批量删除成员")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userIds", value = "用户ID", required = true, dataType = "List"),
    })
    @PostMapping(value = "/batchDelete")
    public Result<String[]> batchDelete(String[] userIds, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpUserService userService = wxCpService.getUserService();
        try {
            userService.delete(userIds);
            return getResult(userIds);
        } catch (WxErrorException e) {
            log.error("更新成员出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 获取部门成员
     *
     * @return
     */
    @ApiOperation("获取部门成员")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "departmentId", value = "部门ID", required = true, dataType = "List"),
            @ApiImplicitParam(paramType = "query", name = "departmentId", value = "是否递归获取子部门下面的成员：1-递归获取，0-只获取本部门", required = true, dataType = "List"),
    })
    @GetMapping(value = "/simplelist")
    public Result<List<WxCpUser>> simplelist(String departmentId, Boolean fetchChild, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpUserService userService = wxCpService.getUserService();
        try {
            List<WxCpUser> wxCpUsers = userService.listSimpleByDepartment(Long.valueOf(departmentId), fetchChild, null);
            return getResult(wxCpUsers);
        } catch (WxErrorException e) {
            log.error("更新成员出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 获取部门成员详情
     *
     * @return
     */
    @ApiOperation("获取部门成员详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "departmentId", value = "部门ID", required = true, dataType = "List"),
            @ApiImplicitParam(paramType = "query", name = "departmentId", value = "是否递归获取子部门下面的成员：1-递归获取，0-只获取本部门", required = true, dataType = "List"),
    })
    @GetMapping(value = "/list")
    public Result<List<WxCpUser>> list(String departmentId, Boolean fetchChild, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpUserService userService = wxCpService.getUserService();
        try {
            List<WxCpUser> wxCpUsers = userService.listByDepartment(Long.valueOf(departmentId), fetchChild, null);
            return getResult(wxCpUsers);
        } catch (WxErrorException e) {
            log.error("更新成员出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 二次验证
     *
     * @param userId  用户ID
     * @param request 请求Request
     * @return
     */
    @ApiOperation("二次验证")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", value = "用户ID", required = true, dataType = "List"),
    })
    @GetMapping(value = "/authsucc")
    public Result<List<WxCpUser>> authsucc(String userId, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpUserService userService = wxCpService.getUserService();
        try {
            userService.authenticate(userId);
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("更新成员出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * openid转userid
     *
     * @param openId  用户ID
     * @param request 请求Request
     * @return
     */
    @ApiOperation("openid转userid")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "openId", value = "用户openId", required = true, dataType = "String"),
    })
    @PostMapping(value = "/openid2UserId")
    public Result<String> openid2UserId(String openId, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpUserService userService = wxCpService.getUserService();
        try {
            String userId = userService.openid2UserId(openId);
            return getResult(userId);
        } catch (WxErrorException e) {
            log.error("openid转userid：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * userid转openid
     *
     * @param userId  用户ID
     * @param request 请求Request
     * @return
     */
    @ApiOperation("userid转openid")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", value = "用户Id", required = true, dataType = "String"),
    })
    @PostMapping(value = "/userId2Openid")
    public Result<Map<String, String>> userId2Openid(String userId, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpUserService userService = wxCpService.getUserService();
        try {
            Map<String, String> resultMap = userService.userId2Openid(userId, Integer.valueOf(wxCpConfig.getAgentId()));
            return getResult(resultMap);
        } catch (WxErrorException e) {
            log.error("userid转openid：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 邀请成员
     *
     * @param userIds  成员ID列表
     * @param partyIds 部门ID列表
     * @param tagIds   标签ID列表
     * @param request
     * @return
     */
    @ApiOperation("邀请成员")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userIds", value = "成员ID列表", required = false, dataType = "List"),
            @ApiImplicitParam(paramType = "query", name = "partyIds", value = "部门ID列表", required = false, dataType = "List"),
            @ApiImplicitParam(paramType = "query", name = "tagIds", value = "标签ID列表", required = false, dataType = "List"),
    })
    @PostMapping(value = "/invite")
    public Result<WxCpInviteResult> invite(List<String> userIds, List<String> partyIds, List<String> tagIds, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpUserService userService = wxCpService.getUserService();
        try {
            WxCpInviteResult inviteResult = userService.invite(userIds, partyIds, tagIds);
            return getResult(inviteResult);
        } catch (WxErrorException e) {
            log.error("邀请成员：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

//    /**
//     * 获取加入企业二维码
//     *
//     * @param sizeType qrcode尺寸类型，1: 171 x 171; 2: 399 x 399; 3: 741 x 741; 4: 2052 x 2052
//     * @param request
//     * @return
//     */
//    @ApiOperation("获取加入企业二维码")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", name = "sizeType", value = "qrcode尺寸类型，1: 171 x 171; 2: 399 x 399; 3: 741 x 741; 4: 2052 x 2052", required = false, dataType = "String"),
//    })
//    @GetMapping(value = "/getJoinQrcode")
//    public Result<String> getJoinQrcode(String sizeType, HttpServletRequest request) {
//
//        // 企业微信基本参数
//        WxCpConfig wxCpConfig = getWxCpConfig(request);
//        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
//        WxCpUserService userService = wxCpService.getUserService();
//        try {
//            String joinQrcode = userService.getJoinQrcode(sizeType);
//            return getResult(joinQrcode);
//        } catch (WxErrorException e) {
//            log.error("获取加入企业二维码：{}", ExceptionUtils.getStackTrace(e));
//            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
//        }
//    }

//    /**
//     * 增量更新成员
//     *
//     * @param wxCpSyncUser 异步用户对象
//     * @param request
//     * @return
//     */
//    @ApiOperation("增量更新成员")
//    @PostMapping(value = "/syncUser")
//    public Result<WxCpSyncUserResult> syncUser(WxCpSyncUser wxCpSyncUser, HttpServletRequest request) {
//
//        // 企业微信基本参数
//        WxCpConfig wxCpConfig = getWxCpConfig(request);
//        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
//        WxCpUserService userService = wxCpService.getUserService();
//        try {
//            WxCpSyncUserResult wxCpSyncUserResult = userService.syncUser(wxCpSyncUser);
//            return getResult(wxCpSyncUserResult);
//        } catch (WxErrorException e) {
//            log.error("增量更新成员：{}", ExceptionUtils.getStackTrace(e));
//            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
//        }
//    }

//    /**
//     * 全量覆盖成员
//     *
//     * @param wxCpSyncUser 异步用户对象
//     * @param request
//     * @return
//     */
//    @ApiOperation("全量覆盖成员")
//    @PostMapping(value = "/replaceUser")
//    public Result<WxCpSyncUserResult> replaceUser(WxCpSyncUser wxCpSyncUser, HttpServletRequest request) {
//
//        // 企业微信基本参数
//        WxCpConfig wxCpConfig = getWxCpConfig(request);
//        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
//        WxCpUserService userService = wxCpService.getUserService();
//        try {
//            WxCpSyncUserResult wxCpSyncUserResult = userService.replaceUser(wxCpSyncUser);
//            return getResult(wxCpSyncUserResult);
//        } catch (WxErrorException e) {
//            log.error("全量覆盖成员：{}", ExceptionUtils.getStackTrace(e));
//            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
//        }
//    }

//    /**
//     * 全量覆盖部门
//     *
//     * @param wxCpSyncUser 异步用户对象
//     * @param request
//     * @return
//     */
//    @ApiOperation("全量覆盖部门")
//    @PostMapping(value = "/replaceParty")
//    public Result<WxCpSyncUserResult> replaceParty(WxCpSyncUser wxCpSyncUser, HttpServletRequest request) {
//
//        // 企业微信基本参数
//        WxCpConfig wxCpConfig = getWxCpConfig(request);
//        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
//        WxCpUserService userService = wxCpService.getUserService();
//        try {
//            WxCpSyncUserResult wxCpSyncUserResult = userService.replaceParty(wxCpSyncUser);
//            return getResult(wxCpSyncUserResult);
//        } catch (WxErrorException e) {
//            log.error("全量覆盖部门：{}", ExceptionUtils.getStackTrace(e));
//            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
//        }
//    }

//    /**
//     * 获取异步任务结果.
//     *
//     * @param jobId 异步任务id，最大长度为64字节
//     */
//    @ApiOperation("获取异步任务结果")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", name = "jobId", value = "异步任务id，最大长度为64字节", required = false, dataType = "String"),
//    })
//    @GetMapping(value = "/replaceParty")
//    public Result<WxCpSyncUserResult> replaceParty(String jobId, HttpServletRequest request) {
//
//        // 企业微信基本参数
//        WxCpConfig wxCpConfig = getWxCpConfig(request);
//        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
//        WxCpUserService userService = wxCpService.getUserService();
//        try {
//            WxCpSyncUserResult wxCpSyncUserResult = userService.getResult(jobId);
//            return getResult(wxCpSyncUserResult);
//        } catch (WxErrorException e) {
//            log.error("获取异步任务结果：{}", ExceptionUtils.getStackTrace(e));
//            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
//        }
//    }

}
